<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>模拟数据检测</title>
		<script src="../../JS/vue.js"></script>
	</head>
	<body>
		<script>
			let data = {
				name: '小莫',
				address: '莫楼',
				a: {
					a: 1
				}
			}
			// 创建一个监视的实例对象
			const obs = new Observer(data)
			console.log(obs)

			// 准备一个vm实例对象
			const vm = new Vue(data)
			vm._data = data = obs

			// console.log(datakey)

			// function recursiveObj(obj) {
			// 	for (let k in obj) {
			// 		if (obj.hasOwnProperty(k)) {
			// 			if (typeof obj[k] == 'object') {
			// 				recursiveObj(obj[k])
			// 			} else {
			// 				console.log(`${k}:${obj[k]}`)
			// 			}
			// 		}
			// 	}
			// }

			// recursiveObj(data)

			function flattenObject(oldObject) {
				const newObject = {}

				flattenHelper(oldObject, newObject, '')

				return newObject

				function flattenHelper(currentObject, newObject, previousKeyName) {
					for (let key in currentObject) {
						let value = currentObject[key]

						if (value.constructor !== Object) {
							if (previousKeyName == null || previousKeyName == '') {
								newObject[key] = value
							} else {
								if (key == null || key == '') {
									newObject[previousKeyName] = value
								} else {
									newObject[previousKeyName + '.' + key] = value
								}
							}
						} else {
							if (previousKeyName == null || previousKeyName == '') {
								flattenHelper(value, newObject, key)
							} else {
								flattenHelper(value, newObject, previousKeyName + '.' + key)
							}
						}
					}
				}
			}

			// const result = flattenObject(oldObject)
			// console.log('result', result)

			function Vue(obj) {
				const keys = Object.keys(obj)
				keys.forEach(k => {
					Object.defineProperty(this, k, {
						get() {
							return data[k]
						},
						set(val) {
							data[k] = val
						}
					})
				})
			}

			// Object.defineProperty(vm, 'name', {
			// 	get() {
			// 		return data.name
			// 	},
			// 	set(val) {
			// 		data.name = val
			// 	}
			// })

			// Object.defineProperty(vm, 'address', {
			// 	get() {
			// 		return data.address
			// 	},
			// 	set(val) {
			// 		data.address = val
			// 	}
			// })

			function Observer(obj) {
				const keys = Object.keys(obj)

				// 遍历
				keys.forEach(k => {
					Object.defineProperty(this, k, {
						get() {
							return obj[k]
						},
						set(val) {
							obj[k] = val
						}
					})
				})
			}
		</script>
	</body>
</html>
